﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxGridView;
using ElingOA6_Admin_DSJCJ.Model;
using System.Data;
using System.IO;
using DevExpress.Utils;
using Newtonsoft.Json;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
      [OutputCache(Duration = 0, VaryByParam = "none")]
    public class FTPManageController : AdminBaseController
    {
        BLL.FTP ftpbll = new BLL.FTP();
        BLL.HRDept hrDeptBLL = new BLL.HRDept();
        BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        string entityNo = GlobalConstant.ENTITYNO;
        BLL.SysBasicCodeName SysBasicCodeNameBLL = new BLL.SysBasicCodeName();
        BLL.DocAttach attbll = new BLL.DocAttach();
        //
        // GET: /Admin/FTPManage/
        [AuthorityActionFilter("m_FTPManage", Order = 1)]
        [LogPageActionFilter("文件上传管理", Order = 2)]

        public ActionResult Index(string pi)
        {
            if (!string.IsNullOrEmpty(pi))
            {
                Session["pi"] = pi;
                ViewData["pageIndex"] = pi;
            }
            if (Session["pi"] == null)
            {
                Session["pi"] = 0;
            }
            ViewData["YearData"] = "";
            ViewData["selYear"] = "";
            ViewData["SysBasicCodeName"] = "";
            ViewData["seldept"] = "";
            ViewData["deptlist"] = "";
            ViewData["MonData"] = "";
            ViewData["selMon"] = "";
            ViewData["isall"] = false;
            if (ftpbll.GetModelList("").Count==0)
            {
                return View("Index", new List<Model.FTP>());
            }
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            if (!string.IsNullOrEmpty(emplNo))
            {

                List<Model.SysBasicCodeName> cmlist = SysBasicCodeNameBLL.GetListByClsNo("SYS_FTP", entityNo);
                ViewData["SysBasicCodeName"] = cmlist;

                if (!ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
                {
                    //无全局下载权限
                    ViewData["isall"] = false;
                    string deptno = "";
                    string deptnname = "";
                    DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                            {
                                ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                deptno = dt.Rows[i]["FDeptNo"].ToString();
                                deptnname = ViewData["DeptName"].ToString();
                                break;
                            }

                        }

                    }
                    //如果是市局
                    Model.HRDept mdept = hrDeptBLL.GetModel(entityNo, deptno);
                    if (mdept.FIsAgency == "N")
                    {
                        List<Model.HRDept> deptList = hrDeptBLL.GetListEntityNo(entityNo);

                        List<SelectListItem> itemList = new List<SelectListItem>();
                        itemList.Add(new SelectListItem() { Text = "市局", Value = "sj" });
                        ViewData["seldept"] = "sj";
                        ViewData["deptlist"] = itemList;
                        getyearandmon();
                        ViewData["FEmplNo"] = emplNo;
                        List<Model.FTP> ftplist = ftpbll.GetModelList("FIsAgency='N'");
                        return View("Index", ftplist);
                    }
                    else
                    {

                        List<Model.HRDept> deptList = hrDeptBLL.GetListEntityNo(entityNo);

                        List<SelectListItem> itemList = new List<SelectListItem>();
                        itemList.Add(new SelectListItem() { Text = deptnname, Value = deptno });

                        //foreach (Model.HRDept model in deptList.Where(c => c.FParentDeptNo == null).ToList())
                        //{
                        //    itemList.Add(new SelectListItem() { Text = model.FDeptName, Value = model.FDeptNo });

                        //}
                        ViewData["seldept"] = deptno;
                        ViewData["deptlist"] = itemList;
                        getyearandmon();
                        ViewData["FEmplNo"] = emplNo;
                        List<Model.FTP> ftplist = ftpbll.GetModelList("dbo.t_FTP.FDeptNo='" + deptno + "'");
                        return View("Index", ftplist);
                    }
                }
                else
                {
                    //全局下载权限
                    ViewData["isall"] = true;
                    List<Model.HRDept> deptList = hrDeptBLL.GetListEntityNo(entityNo);
                    List<SelectListItem> itemList = new List<SelectListItem>();
                    itemList.Add(new SelectListItem() { Text = "所有部门", Value = "all" });
                    itemList.Add(new SelectListItem() { Text = "市局", Value = "sj" });
                    foreach (Model.HRDept model in deptList.Where(c => c.FParentDeptNo == null).ToList())
                    {
                        itemList.Add(new SelectListItem() { Text = model.FDeptName, Value = model.FDeptNo });

                    }
                    ViewData["seldept"] = "all";
                    ViewData["deptlist"] = itemList;
                    getyearandmon();
                    ViewData["FEmplNo"] = emplNo;
                    List<Model.FTP> ftplist = ftpbll.GetModelList("");
                    return View("Index", ftplist);
                }
            }
            else
            {
                Response.Write("<script>alert('请登录');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }

        }

        private void getyearandmon()
        {
            string FYear = "";
            string FMOn = "";
            List<Model.FTP> ftplists = ftpbll.GetModelList("");
            DateTime mint = ftplists.Min(p => p.FInputTime);//取最小日期
            int y = DateTime.Now.Year;
            List<string> yeardata = new List<string>();
            for (int i = mint.Year; i < y + 1; i++)//最小日期的年份开始
            {
                yeardata.Add(i.ToString());
            }
            List<SelectListItem> itemList2 = new List<SelectListItem>();
            //  itemList2.Add(new SelectListItem() { Text = deptnname, Value = deptno });
            foreach (string model in yeardata)
            {
                itemList2.Add(new SelectListItem() { Text = model, Value = model });

            }
            ViewData["YearData"] = itemList2;
            int yout;
            if (!string.IsNullOrEmpty(FYear) & int.TryParse(FYear, out yout))
            {
                ViewData["selYear"] = FYear;
            }
            else
            {
                ViewData["selYear"] = y.ToString();
            }
            List<string> mons = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
            List<SelectListItem> itemList23 = new List<SelectListItem>();
            //  itemList2.Add(new SelectListItem() { Text = deptnname, Value = deptno });
            foreach (string model in mons)
            {
                itemList23.Add(new SelectListItem() { Text = model, Value = model });

            }

            ViewData["MonData"] = itemList23;
            ViewData["selMon"] = "";
            if (!string.IsNullOrEmpty(FMOn) & int.TryParse(FMOn, out yout))
            {
                ViewData["selMon"] = FMOn;
            }
            else
            {
                ViewData["selMon"] = int.Parse(DateTime.Now.Month.ToString());
            }
        }

        public ActionResult UploadLook(string Fid, string deptno)
        {

            ViewData["tourl"] = Url.Content("~/Admin/FTPManage/?pi=" + Session["pi"].ToString());
            BLL.FTP ftpBLL = new BLL.FTP();
            bool alllook = true;
            ViewData["isdisable"] = "";
            string entityNo = GlobalConstant.ENTITYNO;
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            if (!string.IsNullOrEmpty(emplNo))
            {

                try
                {


                    ViewData["DeptName"] = "";
                    ViewData["EmpName"] = "";



                    //获取部门信息


                    DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                            {
                                ViewData["empName"] = dt.Rows[i]["FEmpName"].ToString();
                                ViewData["FEmplNo"] = dt.Rows[i]["FEmplNo"].ToString();
                                ViewData["deptName"] = dt.Rows[i]["FDeptName"].ToString();
                                ViewData["deptNo"] = dt.Rows[i]["FDeptNo"].ToString();
                                OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                break;
                            }

                        }
                    }
                    //如果是市局
                    Model.HRDept mdept = hrDeptBLL.GetModel(entityNo, deptno);
                    if (!ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo)&mdept.FIsAgency=="N")
                    {
                        BLL.Entity entityBLL = new BLL.Entity();
                        BLL.SysBasicCodeName SysBasicCodeNameBLL = new BLL.SysBasicCodeName();
                        List<Model.SysBasicCodeName> cmlist = SysBasicCodeNameBLL.GetListByClsNo("SYS_FTP", entityNo);
                        ViewData["SysBasicCodeName"] = cmlist;
                    
                        Model.FTP mftp = ftpBLL.GetModel(decimal.Parse(Fid));

                        ViewData["FFtpShowText"] = entityBLL.GetAllList().Tables[0].Rows[0]["FFtpShowText"].ToString();
                        string strwhere = " and  FId=" + Fid + " and dbo.t_ftp.FEntityNo=" + entityNo;
                        DataTable dtfile = ftpBLL.GetFtpAndDocAttach(strwhere).Tables[0];
                        List<string> fattachidlist = new List<string>();
                        Dictionary<string, string> attachfiles = new Dictionary<string, string>();
                        foreach (DataRow fr in dtfile.Rows)
                        {
                            fattachidlist.Add(fr["FAttachID"].ToString());
                            attachfiles.Add(fr["FAttachID"].ToString(), fr["FAttachOldFileName"].ToString());
                        }
                        string attachids = JsonConvert.SerializeObject(fattachidlist);
                        ViewData["attachids"] = attachids;
                        ViewData["alllook"] = alllook;
                        ViewData["attachfiles"] = attachfiles;
                        return View("UploadLook", mftp);
                    }
                  else  if (!ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo) & deptno == ViewData["deptNo"].ToString())
                    {
                        BLL.Entity entityBLL = new BLL.Entity();
                        BLL.SysBasicCodeName SysBasicCodeNameBLL = new BLL.SysBasicCodeName();
                        List<Model.SysBasicCodeName> cmlist = SysBasicCodeNameBLL.GetListByClsNo("SYS_FTP", entityNo);
                        ViewData["SysBasicCodeName"] = cmlist;
                      
                        Model.FTP mftp = ftpBLL.GetModel(decimal.Parse(Fid));

                        ViewData["FFtpShowText"] = entityBLL.GetAllList().Tables[0].Rows[0]["FFtpShowText"].ToString();
                        string strwhere = " and  FId=" + Fid + " and dbo.t_ftp.FEntityNo=" + entityNo;
                        DataTable dtfile = ftpBLL.GetFtpAndDocAttach(strwhere).Tables[0];
                        List<string> fattachidlist = new List<string>();
                        Dictionary<string, string> attachfiles = new Dictionary<string, string>();
                        foreach (DataRow fr in dtfile.Rows)
                        {
                            fattachidlist.Add(fr["FAttachID"].ToString());
                            attachfiles.Add(fr["FAttachID"].ToString(), fr["FAttachOldFileName"].ToString());
                        }
                        string attachids = JsonConvert.SerializeObject(fattachidlist);
                        ViewData["attachids"] = attachids;
                        ViewData["alllook"] = alllook;
                        ViewData["attachfiles"] = attachfiles;
                        return View("UploadLook", mftp);
                    }
                    else if (ftpBLL.GetModel(decimal.Parse(Fid)).FEmplNo == emplNo)
                    {
                        BLL.Entity entityBLL = new BLL.Entity();
                        BLL.SysBasicCodeName SysBasicCodeNameBLL = new BLL.SysBasicCodeName();
                        List<Model.SysBasicCodeName> cmlist = SysBasicCodeNameBLL.GetListByClsNo("SYS_FTP", entityNo);
                        ViewData["SysBasicCodeName"] = cmlist;

                        Model.FTP mftp = ftpBLL.GetModel(decimal.Parse(Fid));

                        ViewData["FFtpShowText"] = entityBLL.GetAllList().Tables[0].Rows[0]["FFtpShowText"].ToString();
                        string strwhere = " and  FId=" + Fid + " and dbo.t_ftp.FEntityNo=" + entityNo;
                        DataTable dtfile = ftpBLL.GetFtpAndDocAttach(strwhere).Tables[0];
                        List<string> fattachidlist = new List<string>();
                        Dictionary<string, string> attachfiles = new Dictionary<string, string>();
                        foreach (DataRow fr in dtfile.Rows)
                        {
                            fattachidlist.Add(fr["FAttachID"].ToString());
                            attachfiles.Add(fr["FAttachID"].ToString(), fr["FAttachOldFileName"].ToString());
                        }
                        string attachids = JsonConvert.SerializeObject(fattachidlist);
                        ViewData["attachids"] = attachids;
                        ViewData["alllook"] = alllook;
                        ViewData["attachfiles"] = attachfiles;
                        return View("UploadLook", mftp);

                    }
                    else
                    {
                        alllook = false;
                        ViewData["isdisable"] = "disabled='disabled'";
                        BLL.Entity entityBLL = new BLL.Entity();
                        BLL.SysBasicCodeName SysBasicCodeNameBLL = new BLL.SysBasicCodeName();
                        List<Model.SysBasicCodeName> cmlist = SysBasicCodeNameBLL.GetListByClsNo("SYS_FTP", entityNo);
                        ViewData["SysBasicCodeName"] = cmlist;
                     
                        Model.FTP mftp = ftpBLL.GetModel(decimal.Parse(Fid));

                        ViewData["FFtpShowText"] = entityBLL.GetAllList().Tables[0].Rows[0]["FFtpShowText"].ToString();
                        string strwhere = " and  FId=" + Fid + " and dbo.t_ftp.FEntityNo=" + entityNo;
                        DataTable dtfile = ftpBLL.GetFtpAndDocAttach(strwhere).Tables[0];
                        List<string> fattachidlist = new List<string>();
                        Dictionary<string, string> attachfiles = new Dictionary<string, string>();
                        foreach (DataRow fr in dtfile.Rows)
                        {
                            fattachidlist.Add(fr["FAttachID"].ToString());
                            attachfiles.Add(fr["FAttachID"].ToString(), fr["FAttachOldFileName"].ToString());
                        }
                        string attachids = JsonConvert.SerializeObject(fattachidlist);
                        ViewData["attachids"] = attachids;
                        ViewData["alllook"] = alllook;
                        ViewData["attachfiles"] = attachfiles;
                        return View("UploadLook", mftp);
                    }
                }
                catch (System.Exception ex)
                {
                    Response.Write("<script>alert('操作失败错误代码" + ex.Message.ToString() + "');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }
            }
            else
            {


                //string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                //string deptName = OperateSession.get(GlobalConstant.PARAM_DEPTNAME);
                //string FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                //string empName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                //ViewData["empName"] = empName;
                //ViewData["FEmplNo"] = FEmplNo;
                //ViewData["deptNo"] = deptNo;
                //ViewData["deptName"] = deptName;





                Response.Write("<script>alert('请先登录');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
            return null;
        }
        [ValidateInput(false)]
        public ActionResult Save()
        {
            BLL.FTP ftpBLL = new BLL.FTP();
            try
            {
                string deptName = Fetch.Post("deptName");
                string FLinkTel = Fetch.Post("FLinkTel");
                string FLinkMan = Fetch.Post("FLinkMan");
                string FFTPType = Fetch.Post("FFTPType");
                string FSubject = Fetch.Post("FSubject");
                string deptNo = Fetch.Post("hdeptNo");
                string FEmplNo = Fetch.Post("hFEmplNo");
                string fid = Fetch.Post("hfid");
                Model.FTP f = new Model.FTP();
                f.FDeptNo = deptNo;
                f.FEmplNo = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_FEMPLNO)) ? FEmplNo : OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                f.FFTPType = FFTPType;
                f.FInputTime = DateTime.Now;
                f.FLinkMan = FLinkMan;
                f.FLinkTel = FLinkTel;
                f.FEntityNo = GlobalConstant.ENTITYNO;
                f.FSubject = FSubject;
                f.FID = decimal.Parse(fid);
                ftpbll.Update(f);
                string aids = Fetch.Post("haids");
                string oldaids = Fetch.Post("holdaids");
                List<string> aidlist = JsonConvert.DeserializeObject<List<string>>(aids);
                List<string> oldaidlist = JsonConvert.DeserializeObject<List<string>>(oldaids);
                List<string> aidtodellist = new List<string>();
              
                //获取文件二进制格式
                for (int i=0;i<oldaidlist.Count;i++)
                {
                    if (aidlist[i]=="empty")
                    {
                        aidtodellist.Add(oldaidlist[i].ToString());
                    }
                }
                foreach(string s in aidtodellist)
                {
                 attbll.DeleteDocAttach(decimal.Parse(s));
                }


                string strDefaultAttachPath = Url.Content("/" + "ElingOA6_Admin_DSJCJ" + "/" + "Publish/" + entityNo + "/" + "attach/FTP/" + FFTPType + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0'));
                string url = Server.MapPath(strDefaultAttachPath);
                //如果不存在该文件夹就创建
                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }
                bool hasfile = false;
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    if (Request.Files[i].ContentLength > 0)
                    {
                        hasfile = true;
                    }
                }
               
                System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
                int j = 0;
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    //上传附件
                    if (Request.Files[i].ContentLength > 0 && (uploadFiles.GetKey(i).ToUpper().Contains("UPLOADNAME")))
                    {
                        HttpPostedFileBase upload = Request.Files[i];
                        string type = upload.ContentType;//获取文件类型
                        string extension = Path.GetExtension(upload.FileName).ToLower();
                        long ia = 1;
                        foreach (byte b in Guid.NewGuid().ToByteArray())
                        {
                            ia *= ((int)b + 1);
                        }
                        string result = string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + string.Format("{0:x}", ia - DateTime.Now.Ticks);
                        string fullpath = url + @"\" + result + extension;
                        if (System.IO.File.Exists(fullpath) == true)
                        {
                            
                            ViewData["jsAlert"] = "上传失败";
                            Response.Write("<script>alert('上传失败文件已存在');window.close();</script>");
                            Response.Flush();
                            Response.End();
                            return null;
                            //文件已存在

                        }
                        upload.SaveAs(fullpath);
                        try
                        {
                            ;
                            string strAttachPath = strDefaultAttachPath + "/" + result + extension;
                            string factFileName = Path.GetFileNameWithoutExtension(upload.FileName);//获取文件名称

                            Model.DocAttach docAttachModel = new Model.DocAttach();
                            //获取文件二进制格式

                            System.IO.Stream stream = upload.InputStream;
                            byte[] buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, (int)stream.Length);
                            stream.Close();
                            string docDesc = "";

                            docAttachModel.FEntityNo = entityNo;
                            docAttachModel.FAttachSvrFileName = strAttachPath;
                            docAttachModel.FAttachOldFileName = factFileName + extension;
                            docAttachModel.FAttachContent = buffer;
                            docAttachModel.FAttachFileExt = type;
                            docAttachModel.FAttachType = "FTP";
                            docAttachModel.FAttachDesc = docDesc;
                            docAttachModel.FAttachSource = f.FID;
                            if (!ftpBLL.InsertdocAttach(docAttachModel, f.FID.ToString()))
                            {
                              //  ftpBLL.Delete(f.FID);
                            }

                        }
                        catch (Exception ee)
                        {
                            if (System.IO.File.Exists(fullpath) == true)
                            {
                                System.IO.File.Delete(fullpath);
                            }
                           // ftpBLL.Delete(f.FID);
                            Response.Write("<script>alert('上传失败错误原因" + ee.Message.ToString() + "');window.close();</script>");
                            Response.Flush();
                            Response.End();
                            return null;
                        }
                    }
                }
                ViewData["jsAlert"] = "修改成功";
                //Response.Write("<script>alert('修改成功');window.close();</script>");
                //Response.Flush();
                //Response.End();
                //RedirectToAction("Index", "FTPManage");
                
                //    Response.Write("<script>alert('上传成功 ')</script>");

                ActionResult ac = this.Index(Session["pi"].ToString());
                return ac;
            }
            catch (System.Exception ex)
            {
                Response.Write("<script>alert('上传失败错误原因" + ex.Message.ToString() + "');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
        }


        public ActionResult DownLoadAll()
        {
            BLL.DocAttach docAttachBLL = new BLL.DocAttach();
            string scxzFilePath = Url.Content("~/" + "Publish/scxzFilePath/");//上传下载文件夹路径
            string url = Server.MapPath(scxzFilePath);
            if (!Directory.Exists(url))
            {
                Directory.CreateDirectory(url);
            }
            string strZipPath = System.IO.Path.GetTempPath() + "下载.zip";
           // string strZipPath = Server.MapPath(scxzFilePath + "批量下载.zip");//zip文件路径
            List<DownLoadModel> downLoadList = new List<DownLoadModel>();
            string FIDs = Fetch.Post("hFIDs");
            List<string> fidlist = FIDs.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (string s in fidlist)
            {


                string strZipTopDirectoryPath = scxzFilePath;//需要压缩文件的路径
                string strwhere = " and  FId=" + s + " and dbo.t_ftp.FEntityNo=" + entityNo;
                DataTable dtfile = ftpbll.GetFtpAndDocAttach(strwhere).Tables[0];
                foreach (DataRow dr in dtfile.Rows)
                {

                    DownLoadModel downloadModel = new DownLoadModel();
                    string fullpath = Server.MapPath(Url.Content(dr["FAttachSvrFileName"].ToString()));
                    downloadModel.path = fullpath.Substring(0, fullpath.LastIndexOf('\\') + 1);
                    downloadModel.file = Path.GetFileName(fullpath);
                    downloadModel.deptname = dr["FDeptName"].ToString();
                    downloadModel.subject = dr["FSubject"].ToString();
                    downloadModel.oldfile = dr["FAttachOldFileName"].ToString();
                    downLoadList.Add(downloadModel);

                }
            }
            string tpath=Server.MapPath(Url.Content("/ElingOA6_Admin_DSJCJ/Publish/16/attach/FTP/"));
            Zip.CreateZip2(strZipPath, "", downLoadList);
            //Zip.CreateFileZip(strZipPath, downLoadList);
            return new Common.FileResult() { FilePaht = strZipPath, FileName = "批量下载.zip" };
            //return View("index");

        }
        public ActionResult DownloadSingle(string fid)
        {
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            if (!string.IsNullOrEmpty(emplNo))
            {
                if (ftpbll.FIsAllowLookFtpOrAllowByDept(fid, emplNo, entityNo))
                {
                    BLL.DocAttach docAttachBLL = new BLL.DocAttach();
                    string scxzFilePath = Url.Content("~/" + "Publish/scxzFilePath/");//上传下载文件夹路径
                    string url = Server.MapPath(scxzFilePath);
                    if (!Directory.Exists(url))
                    {
                        Directory.CreateDirectory(url);
                    }

                    string strZipPath = System.IO.Path.GetTempPath() + fid + "下载.zip";
                  //  string strZipPath = Server.MapPath(scxzFilePath + fid + "下载.zip");//zip文件路径
                    List<DownLoadModel> downLoadList = new List<DownLoadModel>();
                    string strZipTopDirectoryPath = scxzFilePath;//需要压缩文件的路径
                    string strwhere = " and dbo.t_FTP.FID='" + fid + "' and dbo.t_ftp.FEntityNo='" + entityNo + "'";
                    DataTable dtfile = ftpbll.GetFtpAndDocAttach(strwhere).Tables[0];
                    string deptn="";
                    string subjectn="";
                    foreach (DataRow dr in dtfile.Rows)
                    {
                    DownLoadModel downloadModel = new DownLoadModel();
                    string fullpath = Server.MapPath(Url.Content(dr["FAttachSvrFileName"].ToString()));
                    downloadModel.path = fullpath.Substring(0, fullpath.LastIndexOf('\\') + 1);
                    downloadModel.file = Path.GetFileName(fullpath);
                    downloadModel.deptname = dr["FDeptName"].ToString();
                   deptn = dr["FDeptName"].ToString();
                    downloadModel.subject = dr["FSubject"].ToString();
                    subjectn = dr["FSubject"].ToString();
                    downloadModel.oldfile = dr["FAttachOldFileName"].ToString();
                    downLoadList.Add(downloadModel);

                     }
                    string tpath=Server.MapPath(Url.Content("/ElingOA6_Admin_DSJCJ/Publish/16/attach/FTP/"));
            Zip.CreateZip2(strZipPath, "", downLoadList);
                     return new Common.FileResult() { FilePaht = strZipPath, FileName =subjectn +          deptn +  "上传文件.zip" };
                
            
            
                    //    DownLoadModel downloadModel = new DownLoadModel();
                    //    string fullpath = Server.MapPath(Url.Content(dr["FAttachSvrFileName"].ToString()));
                    //    downloadModel.path = fullpath.Substring(0, fullpath.LastIndexOf('\\') + 1);
                    //    downloadModel.file = Path.GetFileName(fullpath);
                    //    downLoadList.Add(downloadModel);

                    //}
                  
                    //Zip.CreateFileZip(strZipPath, downLoadList);
                   
                }
                else
                {
                    Response.Write("<script>alert('请没有下载权限');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }
            }
            else
            {
                Response.Write("<script>alert('请登录');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
                
            }
        }

        public string delbyfid(string fid)
        {
            try
            {
                if (ftpbll.Delete(decimal.Parse(fid)))
                {
                    return "ok";
                }
                else
                {
                    return "上传失败当前记录不存在";
                }
            }
            catch (System.Exception ex)
            {
                return "错误代码:" + ex.Message.ToString();
            }

        }
        private string IsNull(string s1, string s2)
        {
            return string.IsNullOrEmpty(s1) ? s2 : s1;
        }
        public ActionResult FTPManageListPartial()
        {
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            if (!string.IsNullOrEmpty(emplNo))
            {
                if (!ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
                {
                    ViewData["isall"] = false;
                }
                else
                {
                    ViewData["isall"] = true;
                }
            }
            ViewData["FEmplNo"] = emplNo;

            var code = Request["code"];
            //  var EMPNAME = Request["EMPNAME"];
            // var DateBegin =Request["DateBegin"];
            //  var DateEnd = Request["DateEnd"];
            var FYear = Request["DateBegin"];
            var FMOn = Request["DateEnd"];
            var dept = IsNull(ComboBoxExtension.GetValue<string>("DEPTS1"), Request["dept"]);
            string strwhere = "1=1";
            if (!string.IsNullOrEmpty(dept) & dept != "all"& dept!="sj")
            {
                strwhere += "and dbo.t_FTP.FDeptNo='" + dept + "' ";
            }
            if (dept=="sj")
            {
                strwhere = "FIsAgency='N'";
            }
            //if (!string.IsNullOrEmpty(DateBegin) || !string.IsNullOrEmpty(DateEnd))
            //{
            //    var begin = string.IsNullOrEmpty(DateBegin) ? DateTime.MinValue.ToString() : DateBegin;
            //    var end = string.IsNullOrEmpty(DateEnd) ? DateTime.MaxValue.ToString() : DateEnd;
            //    strwhere += "and FInputTime > '"+begin+"' and FInputTime < '"+end +"'";
            //}
            int yout;
            if (!string.IsNullOrEmpty(FYear) & int.TryParse(FYear, out yout))
            {
                if (!string.IsNullOrEmpty(FMOn) & int.TryParse(FMOn, out yout))
                {
                    strwhere += " and  DATEDIFF(MM,FInputTime,'" + FYear + "-" + FMOn.PadLeft(2, '0') + "-01')=0";
                }
                else
                {
                    strwhere += " and  DATEDIFF(YEAR,FInputTime,'" + FYear + "-01-01')=0";
                }
            }
            if (!string.IsNullOrEmpty(code))
            {
                strwhere += " and FFTPType='" + code + "'";
            }
            List<Model.FTP> ftplist = ftpbll.GetModelList(strwhere);
            return View(ftplist);
        }
        static GridViewSettings exportGridViewSettings;
        public static GridViewSettings ExportGridViewSettings
        {

            get
            {

                if (exportGridViewSettings == null)

                    exportGridViewSettings = CreateExportGridViewSettings();
                return exportGridViewSettings;
            }
        }
        public static GridViewSettings CreateExportGridViewSettings()
        {
            var setting = new GridViewSettings();
            setting.Name = "gvEditing";
            setting.KeyFieldName = "FID";
            setting.CallbackRouteValues = new { Controller = "FTPManage", Action = "FTPManageListPartial" };
            setting.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            setting.SettingsPager.PageSize = ElingOA6_Admin_DSJCJ.Common.GlobalConstant.CONSTRING_PAGESIZE;
            setting.Columns.Add("FID", "编号");



            setting.Columns.Add("FDeptName", "部门");
            setting.Columns.Add("FLinkMan", "联系人");
            setting.Columns.Add("FSubject", "上传主题");
            setting.Columns.Add("FCodeName", "上传类型");
            setting.Columns.Add("FLinkTel", "联系电话");
            // setting.Columns.Add("FAuditAmount", "补贴金额").CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
            setting.Columns.Add("FInputTimeStr", "上传日期");

            setting.SettingsBehavior.AllowFocusedRow = true;
            setting.SettingsLoadingPanel.Text = "数据读取中...";
            //setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "NSRBM").DisplayFormat = "总计:";
            //setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAuditAmount").DisplayFormat = "￥{0:f2}";

            //setting.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAuditAmount").DisplayFormat = "合计:￥{0}";
            setting.Settings.ShowGroupPanel = true;
            setting.Settings.ShowFooter = true;
            setting.ClientSideEvents.BeginCallback = "function(s,e){OnBeginCallback(s,e)}";
            setting.ClientSideEvents.EndCallback = "function(){}";
            //  setting.Columns["FAuditAmount"].FooterCellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
            setting.SettingsBehavior.EnableCustomizationWindow = true;
            setting.CommandColumn.Visible = true;
            setting.CommandColumn.Width = System.Web.UI.WebControls.Unit.Pixel(5);
            setting.CommandColumn.ShowSelectCheckbox = true;
            setting.CommandColumn.SetHeaderTemplateContent(c =>
            {


                DevExpress.Web.Mvc.UI.ExtensionsFactory.Instance.CheckBox(settingsCheckBox =>
                {
                    settingsCheckBox.Name = "cbSelectAll";
                    settingsCheckBox.Properties.ClientSideEvents.CheckedChanged = string.Format("function(s, e) {{ if(s.GetChecked()) {0}.SelectAllRowsOnPage(); else {0}.UnselectAllRowsOnPage(); }}", setting.Name);

                    if (c.Grid.VisibleRowCount == 0)
                    {
                        settingsCheckBox.Enabled = false;

                    }
                    else
                    {
                        settingsCheckBox.Checked = c.Grid.VisibleRowCount == c.Grid.Selection.Count;
                    }


                }).Render();
            });

            setting.DataBinding = (sender, e) =>
            {
                ASPxGridView grid = (ASPxGridView)sender;
                for (int i = 0; i < grid.AllColumns.Count; i++)
                {
                    if (grid.AllColumns[i].HeaderStyle.HorizontalAlign == System.Web.UI.WebControls.HorizontalAlign.NotSet)
                    {
                        grid.AllColumns[i].HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                    }
                }

            };
            setting.PageIndexChanged = (sender, e) =>
            {
                ASPxGridView grid = (ASPxGridView)sender;
                grid.Selection.UnselectAll();
            };
            return setting;
        }
    }
}
